package com.hc.mailDbService;

import java.util.ArrayList;
import java.util.List;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MailDbManager {
	private MailDataBaseHelper helper;
	private SQLiteDatabase db;
	public MailDbManager(Context context) {
		
		helper = new MailDataBaseHelper(context);
		db = helper.getWritableDatabase();
	}
	/**
	 * 覆盖添加账号记录
	 * @param bean
	 */
	public void addMailAccount(MailBean bean){
			//在添加账户前 ，删除数据库所有的记录
			delMailAccount();
		
		 	db.beginTransaction();	//开始事务
	        try {
	        		db.execSQL("INSERT INTO mailData VALUES( ?, ?, ?, ?)", new Object[]{bean.getSendAddress(),
	        				bean.getSmtpAddress(), bean.getName(), bean.getPwd()});
	        		db.setTransactionSuccessful();	//设置事务成功完成
	        } finally {
	        	db.endTransaction();	//结束事务
	        }
		
	}
	
	public List<MailBean> getMailAccount(){
		

		   ArrayList<MailBean> beans = new ArrayList<MailBean>();
			Cursor c = queryTheCursor();
	       while (c.moveToNext()) {
	    	   MailBean bean = new MailBean();
	    	   bean.setSendAddress(c.getString(c.getColumnIndex("sendAddress")));
	    	   bean.setSmtpAddress(c.getString(c.getColumnIndex("smtpAddress")));
	    	   bean.setName(c.getString(c.getColumnIndex("userName")));
	    	   bean.setPwd(c.getString(c.getColumnIndexOrThrow("pwd")));
	    	   
	    	   beans.add(bean);
	       }
	       c.close();
	       return beans;

	}
	/**
	 * query all log, return cursor
	 * @return	Cursor
	 */
	public Cursor queryTheCursor() {
       Cursor c = db.rawQuery("SELECT * FROM mailData ", null);
       return c;
	}
	
	
	public void delMailAccount(){
		
		
		 db.beginTransaction();	//开始事务
	        try {
	        		db.execSQL("delete from mailData");
	        		db.setTransactionSuccessful();	//设置事务成功完成
	        } finally {
	        	db.endTransaction();	//结束事务
	        }
	}
	
	/**
	 * close database
	 */
	public void closeDB() {
		db.close();
	}
}
